Skip to content

Fix axios session credentials#531

Open
Tanish-Solanki wants to merge 2 commits into
GitMetricsLab:mainfrom
Tanish-Solanki:fix-axios-session-credentials
Open

Fix axios session credentials#531
Tanish-Solanki wants to merge 2 commits into
GitMetricsLab:mainfrom
Tanish-Solanki:fix-axios-session-credentials

Conversation

@Tanish-Solanki
Copy link
Copy Markdown
Contributor

@Tanish-Solanki Tanish-Solanki commented May 26, 2026

Related Issue


Description

Fixed authentication session persistence issues caused by Axios requests not sending credentials/cookies to the backend. Also aligned frontend and backend validation logic to eliminate contradictory signup validation behavior and updated broken mobile navigation tests.

Frontend Changes

Global Axios Configuration
  • Added axios.defaults.withCredentials = true in main.tsx
  • Ensured session cookies (connect.sid) are correctly stored and sent with future requests
Authentication Requests
  • Added { withCredentials: true } to login requests in Login.tsx
  • Added { withCredentials: true } to signup requests in Signup.tsx
Validation Alignment

Updated frontend validation patterns in Signup.tsx to exactly match backend validation rules:

Username Validation
  • Changed from /^[A-Za-z\s]+$/
  • Updated to /^[a-zA-Z0-9_]+$/
  • Allows letters, numbers, and underscores
  • Prevents frontend/backend validation mismatch
Password Validation
  • Updated frontend password regex to:
    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/

  • Requires:

    • uppercase letter
    • lowercase letter
    • number
    • special character
    • minimum 8 characters

Backend Changes

Validator Regex Fix
  • Fixed invalid regex quantifier in authValidator.js
  • Corrected {8,}+ to {8,}
  • Resolved backend validator syntax/import failure

Testing & QA

Navbar Mobile Tests

Updated Navbar.test.tsx to reflect the current navbar structure:

  • Targeted the hamburger menu using its aria-label
  • Updated assertions to match actual tracker links rendered in mobile view
Automated Testing
  • Ran npx vitest run
  • All frontend unit tests passed successfully
Build Validation
  • Executed npm run build
  • Build completed successfully without warnings or bundling errors

How Has This Been Tested?

  • Verified session cookies persist after login/signup
  • Confirmed authenticated requests remain authorized after refresh
  • Tested frontend validation against backend validation rules
  • Verified invalid usernames/passwords are blocked correctly
  • Ran frontend unit tests successfully
  • Confirmed production build succeeds

Type of Change

  • Bug fix
  • New feature
  • Code style update
  • Breaking change
  • Documentation update

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Password requirements now enforce a minimum of 8 characters for increased security
    • Username validation restricted to letters, numbers, and underscores only
    • Improved credential handling to strengthen authentication security
  • Tests

    • Enhanced test suite with more specific accessibility-driven assertions

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 26, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 09b5599
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a19d73b36e5b5000816667d
😎 Deploy Preview https://deploy-preview-531--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 26, 2026

📝 Walkthrough

Walkthrough

The PR fixes a critical authentication bug where session cookies were not persisted due to missing credential flags, enforces minimum password length validation in the backend schema, aligns frontend validation rules with backend requirements, and refactors Navbar tests to use accessibility-driven assertions.

Changes

Authentication Credentials & Validation

Layer / File(s) Summary
Global Axios Credential Configuration
src/main.tsx
Axios now sets withCredentials: true as a global default before React app renders, enabling all subsequent requests to include session cookies in cross-origin calls.
Backend Password Length Enforcement
backend/validators/authValidator.js
Password validation regex quantifier changed from + to {8,} to enforce minimum 8-character length requirement alongside existing uppercase/lowercase/digit/special-character lookaheads.
Frontend Auth Requests & Form Validation
src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx
Login request now explicitly uses withCredentials: true; Signup password validation updated to enforce 8+ characters with required character types; username validation tightened to allow only letters, digits, and underscores.

Navbar Test Accessibility

Layer / File(s) Summary
Mobile Menu & Theme Toggle Accessibility Tests
src/components/__test__/Navbar.test.tsx
Mobile menu visibility tests refactored to locate hamburger button by accessible name, verify menu state by "tracker" link count, and assert theme toggle selection via button role and accessible name index.

Sequence Diagram

sequenceDiagram
  participant Browser
  participant LoginForm as Login Component
  participant AxiosClient as Axios (withCredentials)
  participant AuthAPI as Backend Auth Endpoint
  participant SessionStore as Session Store

  Browser->>LoginForm: Submit credentials
  LoginForm->>AxiosClient: POST /api/auth/login (withCredentials: true)
  AxiosClient->>AuthAPI: Include session cookie in request
  AuthAPI->>SessionStore: Validate and create session
  SessionStore->>AuthAPI: Session created, Set-Cookie header
  AuthAPI->>AxiosClient: 200 + Set-Cookie response
  AxiosClient->>Browser: Store session cookie via credentials flag
  Browser->>LoginForm: Login successful, navigate to /
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Possibly related issues

Possibly related PRs

  • GitMetricsLab/github_tracker#530: Both PRs modify backend/validators/authValidator.js password regex quantifier to enforce minimum 8 characters and update frontend Signup.tsx validation rules identically.
  • GitMetricsLab/github_tracker#464: Both PRs add withCredentials: true credential handling to Login.tsx and Signup.tsx auth requests plus global Axios configuration setup.
  • GitMetricsLab/github_tracker#265: Both PRs modify Signup.tsx client-side password and username validation rules and form submission logic.

Suggested labels

auth, frontend, backend, validation, testing

Poem

🐰 Credentials now flow with the breeze,
Passwords strengthened to eight characters, please!
The session persists through each API call,
And tests dance with a11y—accessible to all!
Form validation's in sync from frontend to back,
No more lost sessions—the auth flow's on track! 🔐

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main objective of fixing axios session credentials, which is the primary focus of the PR.
Description check ✅ Passed The description is comprehensive and follows the template with all required sections (Related Issue, Description, Testing, Type of Change) properly filled out with detailed information.
Linked Issues check ✅ Passed All code changes directly address the requirements in issue #499: axios credentials are properly configured globally and in specific requests, and validation logic is aligned between frontend and backend.
Out of Scope Changes check ✅ Passed All changes are within scope; frontend validation updates, backend regex fix, and test updates align with issue #499's objectives to fix session persistence and eliminate validation mismatches.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Tanish-Solanki
Copy link
Copy Markdown
Contributor Author

Hi @mehul-m-prajapati,
Please review the PR and merge it if everything looks good. Thankyou!

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/pages/Signup/Signup.tsx`:
- Around line 67-69: The live (change-time) username validation in the Signup
component is out of sync with the submit-time validation: update the change-time
check that references formData.username so it uses the same regex
/^[a-zA-Z0-9_]+$/ and update the corresponding error message from "Only letters
are allowed" to "Username can only contain letters, numbers, and underscores"
(or otherwise match the submit-time message) so both validations accept digits
and underscores consistently.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 43cc1e27-bb52-465f-bff8-3679c13df998

📥 Commits

Reviewing files that changed from the base of the PR and between e7b8fc8 and 09b5599.

📒 Files selected for processing (5)
  • backend/validators/authValidator.js
  • src/components/__test__/Navbar.test.tsx
  • src/main.tsx
  • src/pages/Login/Login.tsx
  • src/pages/Signup/Signup.tsx

Comment on lines +67 to +69
: !/^[a-zA-Z0-9_]+$/.test(formData.username)
? "Username can only contain letters, numbers, and underscores"
: "";
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Keep change-time username validation in sync with submit validation.

Lines 67-69 now accept digits and underscores, but the live validation at Line 42 still rejects them with "Only letters are allowed". That leaves usernames like user_1 showing an error while typing even though submit accepts them.

Suggested fix
     if (name === "username") {
       if (!value.trim()) {
         errorMessage = "Username is required";
-      } else if (!/^[A-Za-z\s]+$/.test(value)) {
-        errorMessage = "Only letters are allowed";
+      } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
+        errorMessage = "Username can only contain letters, numbers, and underscores";
       }
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
: !/^[a-zA-Z0-9_]+$/.test(formData.username)
? "Username can only contain letters, numbers, and underscores"
: "";
if (name === "username") {
if (!value.trim()) {
errorMessage = "Username is required";
} else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
errorMessage = "Username can only contain letters, numbers, and underscores";
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/pages/Signup/Signup.tsx` around lines 67 - 69, The live (change-time)
username validation in the Signup component is out of sync with the submit-time
validation: update the change-time check that references formData.username so it
uses the same regex /^[a-zA-Z0-9_]+$/ and update the corresponding error message
from "Only letters are allowed" to "Username can only contain letters, numbers,
and underscores" (or otherwise match the submit-time message) so both
validations accept digits and underscores consistently.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug Report: Login Sessions Lost Immediately — Axios Not Sending Credentials with Requests

1 participant